﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Smart.Service
{
    /// <summary>
    /// 服务调用基类
    /// </summary>
    public class ServiceBase
    {
        /// <summary>
        /// 服务执行
        /// </summary>
        /// <param name="action">命名服务</param>
        /// <param name="parser">命名解析</param>
        /// <param name="method">命名方法</param>
        /// <param name="request">请求对象</param>
        /// <returns></returns>
        protected virtual string InnerExecute(string action, string parser, string method, string request)
        {
            var ctx = Spring.Context.Support.ContextRegistry.GetContext();
            var act = ctx.GetObject(action) as IServiceAction;
            var par = ctx.GetObject(parser) as IServiceParser;

            ///未指定命名方法时，执行默认处理方式
            if (string.IsNullOrEmpty(method))
            {
                var res = act.Execute(par.Parse(request), new XmlServiceResult());
                return res.ToXmlString();
            }

            ///执行命名方法处理方式
            return MethodInvoke(act, method, par.Parse(request));
        }

        /// <summary>
        /// 命名方法处理
        /// </summary>
        /// <param name="action">命名服务</param>
        /// <param name="method">命名方法</param>
        /// <param name="request">请求对象</param>
        /// <returns></returns>
        protected virtual string MethodInvoke(IServiceAction action, string method, IServiceRequest request)
        {
            var info = Spring.Util.ReflectionUtils.GetMethod(action.GetType(), method, new Type[] { typeof(IServiceRequest), typeof(IServiceResult) });
            var res = info.Invoke(action, new object[] { request, new XmlServiceResult() }) as IServiceResult;
            return res.ToXmlString();
        }
    }
}
